package com.template.excel;

import com.template.dto.User;
import com.template.service.UserService;
import com.template.utils.SpringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

public class ExcelImportUtils {

    public static File MultipartFileToFile(MultipartFile multiFile) {
        String fileName = multiFile.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        if (!prefix.equalsIgnoreCase(".xlsx") && !prefix.equalsIgnoreCase(".xls")) {
            return null;
        }

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Boolean importExcel(List<List<Object>> readAll) {
        try {
            for (int i = 1; i < readAll.size(); i++) {
                User user = new User();
                List<Object> objects = readAll.get(i);
                user.setName(String.valueOf(objects.get(0)));
                // 获取当前时间
                LocalDateTime currentDateTime=LocalDateTime.now();

                user.setAccount(currentDateTime.getMinute()+""+ currentDateTime.getSecond() + objects.get(1));
                user.setPassword(String.valueOf(objects.get(2)));
                if(Objects.equals(String.valueOf(objects.get(3)), "男")){
                    user.setSex(1);
                }else if(Objects.equals(String.valueOf(objects.get(3)), "女")){
                    user.setSex(0);
                }else{
                    user.setSex(10);
                }
                user.setPhone(String.valueOf(objects.get(4)));
                user.setState(1);
                user.setImageUrl("https://img1.baidu.com/it/u=3332631198,4273594075&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=481");

                user.setCreateTime(currentDateTime);
//                System.out.println(user);

                // 将用户对象保存到数据库
                UserService userService= SpringUtils.getBean(UserService.class);
                userService.add(user);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

//    public static boolean isExcelFile(File file) {
//        try {
//            Workbook workbook = WorkbookFactory.create(file);
//            return true;
//        } catch (Exception e) {
//            return false;
//        }
//    }
}